<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" width="120%" destroy-on-close @closed="$emit('closed')" align-center fullscreen>
		<el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="70px" label-position="right">
			<el-container>
				<el-header>
					<el-row>
						<el-form-item label="收货日期">
							<!-- <el-date-picker v-model="form.take_deliver_date" type="data" format="YYYY/MM/DD" value-format="YYYY-MM-DD" placeholder="请选择收货日期" /> -->
							<el-date-picker v-model="form.take_deliver_date" :value-format="'YYYY-MM-DD'" type="data" placeholder="请选择收货日期" />
						</el-form-item>
						<el-form-item label="备注">
							<el-input v-model="form.remark" placeholder="请输入备注"></el-input>
						</el-form-item>
						<div style="margin-left:10px">
							<el-button v-if="show" type="primary" @click="startSend">开始收货</el-button>
							<el-button v-else type="primary" @click="stopSend">停止收货</el-button>
						</div>
					</el-row>
				</el-header>
				<el-container>
					<el-aside width="23%">
						<div style="margin: 15px;height:80%">
							<div style="text-align: center;margin: 10px;">条码资料</div>
							<el-form-item label="条码" prop="qrcode">
								<el-input v-model="info.qrcode"
										  @change="handleKeyDown" ref="input"
										  :disabled="weightDis"
								></el-input>
							</el-form-item>
							<el-row>
								<el-col :span="12">
									<el-form-item label="工厂货号" prop="batch_number">
										<el-input v-model="info.batch_number" readonly></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="批次号" prop="style_number" >
										<el-input v-model="info.style_number" readonly></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="12">
									<el-form-item label="承制人" prop="apply">
										<el-input v-model="info.apply" readonly></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="工序" prop="process" >
										<el-input v-model="info.process" readonly></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="12">
									<el-form-item label="颜色" prop="colour">
										<el-input v-model="info.colour" readonly></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="类型" prop="color_number" >
										<el-input v-model="info.color_number" readonly></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="12">
									<el-form-item label="尺码" prop="size">
										<el-input v-model="info.size" readonly></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="数量" prop="num" >
										<el-input v-model="info.num" readonly></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="24">
									<el-form-item label="备注" prop="message">
										<el-input v-model="info.message" readonly></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
					</el-aside>
					<el-main style="height:700px">
						<sc-form-table ref="table" v-model="form.size_data" :addTemplate="addTemplate" placeholder="暂无数据" hideAdd>
							<el-table-column label="工厂货号" prop="factory_number" align="center"></el-table-column>
							<el-table-column label="批次号" prop="batch_number" align="center"></el-table-column>
							<el-table-column label="条码号" prop="barcode" align="center"></el-table-column>
							<el-table-column label="工序" prop="process_title" align="center"></el-table-column>
							<el-table-column label="颜色" prop="colour" align="center"></el-table-column>
							<el-table-column label="尺码" prop="goods_size" align="center"></el-table-column>
							<el-table-column label="数量" prop="num" align="center"></el-table-column>
							<el-table-column label="备注" prop="remark" align="center"></el-table-column>
						</sc-form-table>
					</el-main>
				</el-container>
			</el-container>
		</el-form>
	</el-dialog>
	<!-- 收货停止 -->
	<el-dialog v-model="dialog.send" title="此次收货停止,是否提交?" width="500" :before-close="handleClose" align-center>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialog.send = false">取消</el-button>
				<el-button type="primary" @click="submit">确定</el-button>
				<el-button type="primary" @click="submit">确定并打印收货单</el-button>
			</div>
		</template>
	</el-dialog>
	<!-- 件数修正 -->
	<el-dialog v-model="dialog.weight" title="件数修正" width="500" :before-close="handleClose" align-center>
		<el-form-item label="请输入正确的件数" prop="edit_number" >
			<el-input v-model="info.edit_number"></el-input>
		</el-form-item>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialog.weight = false">取消</el-button>
				<el-button type="primary" @click="numSub">确定</el-button>
			</div>
		</template>
	</el-dialog>
</template>
<script>
export default {
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '后整扫码收货',
				edit: '编辑仓库',
				show: '查看'
			},
			visible: false,
			isSaveing: false,
			dialog:{
				send:false,
				weight:false,
			},
			//表单数据
			form: {
				remark:"",
				take_deliver_date: new Date().toISOString().slice(0, 10),
				delivery_method:2,
				size_data:[],
				process_id: 8,
			},
			info:{
				qrcode:"",
				batch_number: "",
				style_number: "",
				apply: "",
				process: "",
				colour: "",
				size: "",
				num: "",
				message: "",
				weight:"",
				expected_number:"",
				weight_num:"",
				edit_number:'',
                original_barcode:"",
			},
			weight:"",
			addTemplate: {},
			show:true,
			apply:[],
			weightDis:true,
			ports: [],
			port:{},
			connected:null,
			reader:null,
			message:null,
			serialOptions:{
				baudRate: 9600,
				flowControl: 'none',
				dataBits: 8
			},
			infoData:{},
		}
	},
	mounted () {
		// if ("serial" in navigator) {
		// 	this.chooseSerial()
		// } else {
		// 	console.log(false);
		// }
	},
	created() {
		// this.autoConnectSerial();
	},
	unmounted() {
		this.cutPort()
	},
	methods: {
		// 手动连接
		async chooseSerial(){
			try {
				this.port = await navigator.serial.requestPort();
				this.ports = await navigator.serial.getPorts();
				console.log('this.port :>> ', this.port);
				this.openSear()
			} catch (error) {
				this.$alert(error, "提示", { type: 'error' })
				return;
			}
		},
		// 自动连接
		// async autoConnectSerial() {
		//     try {
		//         const ports = await navigator.serial.getPorts();
		//         if (ports.length > 0) {
		//             // 如果有可用端口，直接选择第一个端口进行连接
		//             this.port = ports[0];
		//             await this.openSear();
		//         } else {
		//             this.$alert("未找到可用串口", "提示", { type: 'error' });
		//         }
		//     } catch (error) {
		//         this.$alert(error, "提示", { type: 'error' });
		//     }
		// },
		async openSear(){
			try {
				await this.port.open(this.serialOptions)
				this.reader = this.port.readable.getReader()
				this.connected = true
				this.readLoop()
			} catch (error) {
				this.$alert(error, "提示", { type: 'error' })
				return;
			}
		},
		async readLoop() {
			try {
				while (this.connected) {
					const { value, done } = await this.reader.read()
					if (done) {
						this.reader.releaseLock()
						break
					}
					this.message = new TextDecoder().decode(value)
					if(this.message.length==18){
						let unit = this.message.substr(14,2).toString()
						let weight = this.message.substr(7,7).trim()
						if(unit!='kg'){
							this.info.weight = weight / 1000
						}else{
							this.info.weight = weight
						}
						// let base = this.message.substr(0,2)
						// if(base=='ST'){
						//     console.log('这里是稳定的输出');
						//     let type = this.message.substr(3,2)
						//     if(type=='TR'){
						//         let unit = this.message.substr(14,2).toString()
						//         let weight = this.message.substr(7,7).trim()
						//         if(unit!='kg'){
						//             this.info.weight = weight / 1000
						//         }else{
						//             this.info.weight = weight
						//         }
						//         console.log('这里是去皮的输出',this.info.weight);
						//     }
						// }
					}
				}
			} catch (error) {
				this.$alert(error, "提示", { type: 'error' })
			}
		},
		// 断开串口
		async cutPort(){
			if (this.port && this.connected) {
				await this.reader.cancel();
				await this.port.close();
				this.port = "";
			} else {
				// this.$alert("错误", "提示", { type: 'error' })
				console.log('11')
			}
		},
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit() {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					this.dialog.send = false
					var res = [];
					res = await this.$API.produce.contract.loomScanTakeDelivery.post(this.form);
					this.isSaveing = false;
					if (res.code == 1) {
						this.cutPort()
						this.$emit('success', this.form, this.mode)
						this.visible = false;
						this.$message.success("操作成功")
					} else {
						this.$alert(res.message, "提示", { type: 'error' })
					}
				} else {
					return false;
				}
			})
		},
		/**开始收货*/
		startSend(){
			this.show = false
			this.weightDis = false
			this.$nextTick(()=>{
				this.$refs.input.focus()
				this.$refs.input.$el.setAttribute('lang', 'en');
			})
		},
		/**停止收货*/
		stopSend(){
			this.dialog.send = true
			this.cutPort()
		},
		/**扫码枪事件*/
		async handleKeyDown(e) {
			this.info.qrcode = ''
			var res = await this.$API.produce.contract.loomScanOrderDetail.get({qrcode: e, process_id:8});
			if(res.code==1){
				this.infoData = res.data
				this.info.batch_number = res.data.contract.batch_number
				this.info.style_number = res.data.contract.goods.style_name
				this.info.apply = res.data.contract.referred_as
				this.info.process = res.data.contract.process_title
				this.info.colour = res.data.contract.goods.colour
				this.info.color_number = res.data.contract.goods.color_type == 1 ? "主色" : "加色"
				this.info.size = res.data.detail.goods_size
				this.info.num = Number(res.data.detail.curr_num)
				this.info.weight_num = res.data.detail.curr_num
				this.info.message = res.data.contract.remark
				this.info.barcode = res.data.detail.barcode
                this.info.original_barcode = res.data.detail.original_barcode
				this.info.expected_number = Math.ceil(Number(this.info.weight*1000) / Number(res.data.detail.weight))
				this.info.edit_number =  res.data.detail.curr_num
				if(this.info.expected_number > (this.info.num+1) || this.info.expected_number < (this.info.num-1)){
					if(this.info.expected_number > (this.info.num+1)){
						this.dialog.weight = true
					}
					if(this.info.expected_number < (this.info.num-1) ){
						this.dialog.weight = true
					}
				}else{
					let tabData = []
					tabData.push({
						contract_no : res.data.contract.contract_no,
						batch_number : res.data.contract.batch_number,
						factory_number : res.data.contract.factory_number,
						process : res.data.contract.process_title,
						colour : res.data.contract.goods.colour,
						goods_size : res.data.detail.goods_size,
						num : this.info.weight_num,
						remark : res.data.contract.remark,
						weight : this.info.weight,
						total_weight : this.info.weight,
						goods_id : res.data.detail.goods_id,
						process_title : res.data.contract.process_title,
						overnumber : this.info.expected_number - res.data.detail.curr_num,
						overweight : (this.info.weight - Number(res.data.detail.curr_num * res.data.detail.weight/1000)).toFixed(2),
						barcode:this.info.barcode,
                        original_barcode : res.data.detail.original_barcode
					})
					// this.form.size_data = tabData
					let existingIds = this.form.size_data.map(item => item.original_barcode);
					for(let i = tabData.length - 1; i >= 0; i--){
						if(existingIds.includes(tabData[i].original_barcode)){
							this.$alert('请勿重复扫码!', "提示", { type: 'error' })
							tabData.splice(i, 1);
						}
					}
					this.form.size_data = [...this.form.size_data,...tabData]
				}
			}else{
				this.$alert(res.message, "提示", { type: 'error' })
			}
		},
		/**修正确定按钮点击*/
		numSub(){
			this.dialog.weight = false
			let tabData = []
			tabData.push({
				contract_no : this.infoData.contract.contract_no,
				batch_number : this.infoData.contract.batch_number,
				factory_number : this.infoData.contract.factory_number,
				process : this.infoData.contract.process_title,
				colour : this.infoData.contract.goods.colour,
				goods_size : this.infoData.detail.goods_size,
				num : this.info.edit_number,
				remark : this.infoData.contract.remark,
				weight : this.info.weight,
				total_weight : this.info.weight,
				goods_id : this.infoData.detail.goods_id,
				process_title : this.infoData.contract.process_title,
				overnumber : this.info.expected_number - this.infoData.detail.curr_num,
				overweight : (this.info.weight - Number(this.infoData.detail.curr_num * this.infoData.detail.weight/1000)).toFixed(2),
				barcode:this.info.barcode,
                original_barcode : this.info.original_barcode
			})
			// this.form.size_data = tabData
			let existingIds = this.form.size_data.map(item => item.original_barcode);
			for(let i = tabData.length - 1; i >= 0; i--){
				if(existingIds.includes(tabData[i].original_barcode)){
					this.$alert('请勿重复扫码!', "提示", { type: 'error' })
					tabData.splice(i, 1);
				}
			}
			this.form.size_data = [...this.form.size_data,...tabData]
		},
	}
}
</script>

<style></style>
